const audio = document.querySelector("audio.music"); // 获取audio元素
const playBtn = document.querySelector("#playBtn"); // 播放按钮
const prevBtn = document.querySelector("#prevBtn"); // 上一首按钮
const nextBtn = document.querySelector("#nextBtn"); // 下一首按钮
const cd = document.querySelector("div div.cd");
const lyric = document.querySelector(".lyrics ul"); // 歌词
const title = document.querySelector("div.title h1");
const artist = document.querySelector("div.title h2");
const time = document.querySelector("p.time");
const slider = document.querySelector(".slider");
const plant = document.querySelector("div.mask .button");
const list = document.querySelector("div.list ul");
const listButton = document.querySelector("div.musicList .button");
const container = document.querySelector("div.container");
const main = document.querySelector(".main");
const control = document.querySelector(".control");
const listContainer = document.querySelector("div.list");
const random = document.querySelector("#random");
const single = document.querySelector("#single");
let play = { random: 0, single: 0 };
let flag = 0;
let r_temp;
let musicList = [];
let lyricList = [];
let index = 0; // 当前播放的歌曲索引
function selected(e) {
  index = 0;
  musicList = [];
  list.innerHTML = "";
  let files = e.target.files;
  for (let i = 0; i < files.length; i++) {
    let file = files[i];
    if (
      file.type === "audio/mpeg" ||
      file.type === "audio/wav" ||
      file.type === "audio/ogg"
    ) {
      musicList.push(file);
      let li = document.createElement("li");
      let num = musicList.length - 1;
      (function (num) {
        li.onclick = function () {
          if (index != num) {
            index = num;
            nextMusic(2);
          }
        };
      })(num);
      li.innerHTML = `<h2>${file.name.split("-")[1].slice(0, -4)}</h2>
            <p>${file.name.split("-")[0]}</p>`;
      list.appendChild(li);
    } else if (file.type == "") lyricList.push(file);
  }
  document.querySelector(
    ".button-content"
  ).innerText = `已选择${musicList.length}首歌曲`;
  renderPlay();
  getMp3Tag(musicList[index], index, function () {
    render();
    onend();
  });
}
//加载音频文件
function loadMusic(index, fun) {
  let fileReader = new FileReader();
  fileReader.readAsDataURL(musicList[index]);
  fileReader.onload = function () {
    fun(fileReader.result);
  };
}
//读取歌词文件
function readLocalFile(file, callback) {
  var reader = new FileReader();
  reader.onload = function (event) {
    var content = event.target.result;
    callback(content);
  };
  reader.readAsText(file);
}
function getMp3Tag(file, index, fun) {
  jsmediatags.read(file, {
    onSuccess: function (tag) {
      let base64String = "";
      file.title = tag.tags.title;
      file.artist = tag.tags.artist;
      file.cover = tag.tags.picture
        ? (function () {
            for (i = 0; i < tag.tags.picture.data.length; i++)
              base64String += String.fromCharCode(tag.tags.picture.data[i]);
            return window.btoa(base64String);
          })()
        : null;
      file.format = tag.tags.picture ? tag.tags.picture.format : null;
      if (tag.tags.lyrics) {
        file.lyric = tag.tags.lyrics.lyrics;
        fun();
      } else {
        try {
          lyricList.forEach((e, i) => {
            if (e.name.includes(file.name.slice(0, -4))) {
              readLocalFile(lyricList[i], function (text) {
                file.lyric = text;
              });
              throw new Error("break");
            } else {
              file.lyric = "[00:00.00]此歌曲暂时没有歌词哦~";
            }
          });
        } catch (e) {
          if (e.message === "break") {
          } else {
            throw e; // 将其他异常继续抛出
          }
        }
        fun();
      }
    },
    onError: function (error) {
      console.log("Error: ", error.type, error.info);
    },
  });
}
// 加载歌词
function loadLyric(lyrics) {
  // 解析歌词
  renderLyric(lyrics);
  lyric.parentNode.onwheel = function () {
    clearTimeout(r_temp);
    flag = 1;
    r_temp = setTimeout(() => {
      flag = 0;
    }, 2000);
  };
}
function onend() {
  audio.onended = function () {
    nextMusic();
  };
}
// 播放音乐
let interval;
function playMusic() {
  audio.play();
  interval = setInterval(function () {
    renderLyric(musicList[index].lyric);
  }, 100);
}

// 暂停音乐
function pauseMusic() {
  audio.pause();
  clearInterval(interval);
}

// 上一首
function prevMusic(manual = 0) {
  if (manual == 1)
    if (play.random) {
      index = getRandomNumber(0, musicList.length - 1);
    } else {
      index--;
      if (index < 0) {
        index = musicList.length - 1;
      }
    }
  else if (!play.single) {
    if (play.random) {
      index = getRandomNumber(0, musicList.length - 1);
    } else {
      index--;
      if (index < 0) {
        index = musicList.length - 1;
      }
    }
  }
  renderPlay();
  getMp3Tag(musicList[index], index, function () {
    render();
  });

  playBtn.classList.remove("icon-bofang");
  playBtn.classList.add("icon-24gf-pause2");
  plant.classList.remove("icon-24gf-pause2");
  plant.classList.add("icon-bofang");
  cd.style.animationPlayState = "running";
}
function render() {
  loadMusic(index, function (result) {
    audio.src = result;
    slider.value = 0;
    cd.style.background = musicList[index].cover
      ? `url(data:${musicList[index].format};base64,${musicList[index].cover}) no-repeat center center`
      : "url(./img/favicon.ico) no-repeat center center";
    cd.style.backgroundSize = "cover";
    title.innerText = musicList[index].title;
    artist.innerText = musicList[index].artist;

    audio.oncanplaythrough = function () {
      time.childNodes[2].innerText = `${String(
        Math.floor(Number(audio.duration) / 60)
      ).padStart(2, 0)}:${String(
        Math.floor(Number(audio.duration)) % 60
      ).padStart(2, 0)}`;
    };
    auidoPlay();
    loadLyric(musicList[index].lyric);
  });
}
// 下一首
function nextMusic(manual) {
  if (manual == 1)
    if (play.random) {
      index = getRandomNumber(0, musicList.length - 1);
    } else {
      index++;
      if (index >= musicList.length) {
        index = 0;
      }
    }
  else if (manual != 2)
    if (!play.single) {
      if (play.random) {
        index = getRandomNumber(0, musicList.length - 1);
      } else {
        index++;
        if (index >= musicList.length) {
          index = 0;
        }
      }
    }
  renderPlay();
  getMp3Tag(musicList[index], index, function () {
    render();
  });
  playBtn.classList.remove("icon-bofang");
  playBtn.classList.add("icon-24gf-pause2");
  plant.classList.remove("icon-bofang");
  plant.classList.add("icon-24gf-pause2");
  cd.style.animationPlayState = "running";
}
function auidoPlay() {
  if (audio.paused) {
    if (musicList.length) {
      playMusic();
      playBtn.classList.remove("icon-bofang");
      playBtn.classList.add("icon-24gf-pause2");
      plant.classList.remove("icon-bofang");
      plant.classList.add("icon-24gf-pause2");

      cd.style.animationPlayState = "running";
    } else {
      alert("请选择需要播放的文件夹");
    }
  } else {
    pauseMusic();
    playBtn.classList.remove("icon-24gf-pause2");
    playBtn.classList.add("icon-bofang");
    plant.classList.remove("icon-24gf-pause2");
    plant.classList.add("icon-bofang");
    cd.style.animationPlayState = "paused";
  }
}
// 渲染歌词
function renderLyric(lyricText) {
  let fun = () => {
    let t = lyricText
      ? lyricText.trim().split("\n")
      : ["[00:00.00]此歌曲暂时没有歌词哦~"];
    t.forEach((e, i) => {
      t[i] =
        Number(t[i].slice(1, 3)) * 60 +
        Number(t[i].slice(4, 6)) +
        Number(t[i].slice(6, 9));
    });
    return t;
  };
  let timeArr = fun();
  let lyricArr = lyricText?.replaceAll(/\[.*?\]/g, "").split("\n");
  let lyricHTML = "";
  if (lyricArr[lyricArr.length - 1].trim() == "") lyricArr.pop();
  console.log(lyricArr, timeArr);
  for (let i = 0; i < lyricArr?.length; i++) {
    if (
      (timeArr[i] <= audio.currentTime && timeArr[i + 1] > audio.currentTime) ||
      (lyricArr.length - 1 == i && timeArr[i] <= audio.currentTime) ||
      lyricArr.length == 1
    )
      lyricHTML += `<li class="render">${lyricArr[i]}</li>`;
    else lyricHTML += `<li>${lyricArr[i]}</li>`;
  }
  lyric.innerHTML = lyricHTML;
  if (!flag) {
    lyric.querySelector("li.render")?.scrollIntoView({
      behavior: "smooth",
      block: "center",
    });
    flag = 1;
    clearTimeout(r_temp);
    r_temp = setTimeout(() => {
      flag = 0;
    }, 300);
  }
  renderTime();
  updateProgress();
  updataSlider();
}
function updataSlider() {
  slider.style.background = `linear-gradient(to right,#6eb6ff 0%,#b0d7ff ${
    (audio.currentTime / audio.duration) * 100
  }%,aliceblue ${(audio.currentTime / audio.duration) * 100}%,aliceblue 100%)`;
}
function renderTime() {
  time.childNodes[0].innerText = `${String(
    Math.floor(Number(audio.currentTime) / 60)
  ).padStart(2, 0)}:${String(
    Math.floor(Number(audio.currentTime)) % 60
  ).padStart(2, 0)}`;
}
function updateProgress(val) {
  if (val) {
    audio.currentTime = (val / 1000) * audio.duration;
  }
  slider.value = (audio.currentTime / audio.duration) * 1000;
}
//打开播放列表
function showList() {
  if (container.style.width == "1150px") {
    container.style.width = " 800px";
    main.style.left = "50%";
    control.style.left = "51%";
    listContainer.style.opacity = 0;
    listButton.style.transform = " rotateY(0deg)";
    setTimeout(function () {
      listContainer.style.display = "none";
    }, 1000);
  } else {
    container.style.width = "1150px";
    main.style.left = "32%";
    control.style.left = "32%";
    listButton.style.transform = " rotateY(180deg)";
    setTimeout(function () {
      listContainer.style.opacity = 1;
    }, 100);

    listContainer.style.display = "block";
    renderPlay();
  }
}
//为正在播放音乐着色
function renderPlay() {
  let li = list.querySelectorAll("li")[index];
  list.querySelectorAll("li").forEach((e, i) => {
    if (i != index)
      e.style.backgroundImage =
        " linear-gradient(to right, #8ec5fc 0%, #8ec5fca0 100%)";
  });
  if (li) {
    li.style.backgroundImage =
      "linear-gradient(-60deg, #8ec5fc 0%, #e0c3fc 100%)";
    li.scrollIntoView({
      behavior: "smooth",
      block: "center",
    });
  }
}
//生成任意区间随机数
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
//是否随机播放
function randomPlay() {
  if (play.random) {
    play.random = 0;
    random.style.color = "#22222280";
  } else {
    play.random = 1;
    random.style.color = "#000";
  }
} //是否单曲循环播放
function singlePlay() {
  if (play.single) {
    play.single = 0;
    single.style.color = "#22222280";
  } else {
    play.single = 1;
    single.style.color = "#000";
  }
}
prevBtn.onclick = function () {
  prevMusic(1);
};
nextBtn.onclick = function () {
  nextMusic(1);
};
playBtn.onclick = auidoPlay;
cd.onclick = auidoPlay;
listButton.onclick = showList;
random.onclick = randomPlay;
single.onclick = singlePlay;
